//
//  AddressModel.m
//  EncryptionTPB
//
//  Created by LvJianfeng on 15/9/15.
//  Copyright © 2015年 coderjianfeng. All rights reserved.
//

#import "AddressModel.h"
#import "Person.h"
@import Contacts;

@interface AddressModel()
@property (strong, nonatomic) NSMutableArray *contacts;
@end

@implementation AddressModel
/**
 *  加载本地通讯录名称得首字母
 *
 *  @return 返回首字母数组
 */
+ (void)checkFirstAuthLoad{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
}
/**
 *  加载本地通讯录名称得首字母
 *
 *  @return 返回首字母数组
 */
//这边需要优化，没必要去读取两次
- (NSArray *)loadIndexAddressBook:(AddressTableViewController*)controller{
    BOOL isAuth = [self checkAddressBookAuthorizationStatus:controller];
    if (isAuth) {
        return [ChineseString IndexArray:self.contacts];
    }
    return nil;
}
/**
 *  加载本地通讯录,返回本地通讯录联系人
 *
 *  @param controller 控制器
 */
- (NSArray*)loadLocalAddressBook:(AddressTableViewController*)controller{
    BOOL isAuth = [self checkAddressBookAuthorizationStatus:controller];
    if (isAuth) {
        /**
         *  返回前，处理数据
         */
        return [NSArray arrayWithArray:[ChineseString LetterSortArray:self.contacts]];
    }
    return nil;
}
/**
 *  检查获取通讯录访问权限
 *
 *  @param controller 控制器
 *
 *  @return 是否具有访问权限BOOL
 */
- (BOOL)checkAddressBookAuthorizationStatus:(AddressTableViewController*)controller{
    /**
     获取权限访问通讯录
     
     :returns: Bool
     */
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    //ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
    CNAuthorizationStatus authStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (authStatus != CNAuthorizationStatusAuthorized) {
        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!granted) {
                [JFUtil showMBAlertLabel:controller.view text:@"通讯录未授权访问，请在设置->隐私中允许程序访问" afterDelay:2.0];
                return;
            }
        }];
    }
    /**
     *  读取本机联系人
     *  @[[CNContact descriptorForAllComparatorKeys]]
     */
    NSError *error;
    CNContactFormatter *formatter= [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName];
    
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[formatter,CNContactImageDataKey,CNContactPhoneNumbersKey,CNContactPostalAddressesKey,CNContactEmailAddressesKey,CNContactUrlAddressesKey,CNContactDepartmentNameKey,CNContactJobTitleKey]];
    [contactStore enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        [self.contacts addObject:contact];
        
        //暂时不用，有问题，等开发业务层得时候用CoreModel//[self insertContactToSTPB:contact];
    }];
    return YES;
}
/**
 *  插入数据库
 *
 *  @param contact 联系人对象
 */
- (void)insertContactToSTPB:(CNContact*)contact{
    Person *person = [Person new];
    person.uid = 1;
    person.name = [CNContactFormatter stringFromContact:contact style:CNContactFormatterStyleFullName];
    person.organization = contact.organizationName;
    person.department = contact.departmentName;
    person.jobTitle = contact.jobTitle;
    person.note = @"note";
    person.telephone = @"telephone";
    person.avatarUrl = @"avatar";
    if (contact.emailAddresses.count>0) {
        person.email = contact.emailAddresses[0].value;
    }
    
    if (contact.phoneNumbers.count>0) {
        person.phone = [(CNPhoneNumber*)contact.phoneNumbers[0].value stringValue];
    }
    if (contact.postalAddresses.count>0) {
        CNPostalAddress *address = contact.postalAddresses[0].value;
        person.country = @"country";//address.country;
        person.state = @"state";//address.state;
        person.city = @"city";//address.city;
        person.street = @"street";//address.street;
        person.zip = @"zip";//address.postalCode;
        person.countryCode = @"countryCode";//address.ISOCountryCode;
    }
    //执行数据库插入操作
    BOOL isOK = [Person insert:person];
    if (isOK) {
        DDDLog(@"插入成功");
    }
}

#pragma mark lazyload
- (NSMutableArray *)contacts{
    if (!_contacts) {
        _contacts = [[NSMutableArray alloc] init];
    }
    return _contacts;
}
@end
